package com.test.hibernate.hql.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/9/21 8:35
 */
public class HibernateUtils {
    private static HibernateUtils instance = new HibernateUtils();
    private SessionFactory sessionFactory;

    private HibernateUtils() {
    }

    public static HibernateUtils getInstance() {
        return instance;
    }

    public SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        return sessionFactory;
    }

    public Session getSesssion() {
        return getSessionFactory().getCurrentSession();
    }
}
